// 1. 首先创建团队成员控制器
package com.chuangshu.chuangshuteam.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chuangshu.chuangshuteam.annotation.RequiresPermissions;
import com.chuangshu.chuangshuteam.config.BaseContext;
import com.chuangshu.chuangshuteam.dto.Result;
import com.chuangshu.chuangshuteam.entity.Role;
import com.chuangshu.chuangshuteam.entity.TeamMember;
import com.chuangshu.chuangshuteam.mapper.RoleMapper;
import com.chuangshu.chuangshuteam.mapper.TeamMemberMapper;
import com.chuangshu.chuangshuteam.service.AuthService;
import com.chuangshu.chuangshuteam.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/team/members")
public class TeamMemberController {

    @Autowired
    private TeamMemberMapper teamMemberMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private AuthService authService;

    @Autowired
    private UsersService usersService;

    /**
     * 设置成员角色（仅管理员）
     */
    @PutMapping("/{memberId}/role")
    @RequiresPermissions("team:manage:role")
    public Result setMemberRole(@PathVariable Long memberId, @RequestBody RoleUpdateRequest request) {
        Long currentUserId = BaseContext.getCurrentId();

        // 检查当前用户是否为管理员
        if (!authService.isAdmin(currentUserId)) {
            return Result.fail("无权限操作");
        }

        // 查找团队成员
        TeamMember teamMember = teamMemberMapper.selectById(memberId);
        if (teamMember == null) {
            return Result.fail("成员不存在");
        }

        // 获取角色ID
        Role role = getRoleByRoleName(request.getRole());
        if (role == null) {
            return Result.fail("无效的角色");
        }

        // 更新角色
        teamMember.setRoleId(role.getId());
        teamMemberMapper.updateById(teamMember);

        log.info("设置成员角色: memberId={}, role={}, operatorId={}",
                memberId, request.getRole(), currentUserId);

        return Result.ok("角色设置成功");
    }

    /**
     * 设置成员专业方向
     */
    @PutMapping("/{memberId}/direction")
    public Result setMemberDirection(@PathVariable Long memberId, @RequestBody DirectionUpdateRequest request) {
        Long currentUserId = BaseContext.getCurrentId();

        // 查找团队成员
        TeamMember teamMember = teamMemberMapper.selectById(memberId);
        if (teamMember == null) {
            return Result.fail("成员不存在");
        }

        // 检查权限：管理员或自己可以修改方向
        if (!authService.isAdmin(currentUserId) &&
                !teamMember.getUserId().equals(currentUserId)) {
            return Result.fail("无权限操作");
        }

        // 验证方向是否有效
        String[] validDirections = {"frontend", "backend", "ui", "cv", "pm", "embedded"};
        boolean isValid = false;
        for (String dir : validDirections) {
            if (dir.equals(request.getDirection())) {
                isValid = true;
                break;
            }
        }

        if (!isValid) {
            return Result.fail("无效的专业方向");
        }

        // 更新方向
        teamMember.setDirection(request.getDirection());
        teamMemberMapper.updateById(teamMember);

        // 同时更新用户表中的方向
        usersService.setDirection(teamMember.getUserId(), request.getDirection());

        log.info("设置成员方向: memberId={}, direction={}, operatorId={}",
                memberId, request.getDirection(), currentUserId);

        return Result.ok("专业方向设置成功");
    }

    /**
     * 移除团队成员（仅管理员）
     */
    @DeleteMapping("/{memberId}")
    @RequiresPermissions("team:manage:remove")
    public Result removeMember(@PathVariable Long memberId) {
        Long currentUserId = BaseContext.getCurrentId();

        // 检查当前用户是否为管理员
        if (!authService.isAdmin(currentUserId)) {
            return Result.fail("无权限操作");
        }

        // 查找团队成员
        TeamMember teamMember = teamMemberMapper.selectById(memberId);
        if (teamMember == null) {
            return Result.fail("成员不存在");
        }

        // 检查是否删除自己
        if (teamMember.getUserId().equals(currentUserId)) {
            return Result.fail("不能移除自己");
        }

        // 检查是否是唯一的管理员
        if (isLastAdmin(teamMember.getUserId())) {
            return Result.fail("不能移除唯一的管理员");
        }

        // 从团队中移除成员
        teamMemberMapper.deleteById(memberId);

        log.info("移除团队成员: memberId={}, userId={}, operatorId={}",
                memberId, teamMember.getUserId(), currentUserId);

        return Result.ok("成员移除成功");
    }

    /**
     * 根据角色名称获取角色
     */
    private Role getRoleByRoleName(String roleName) {
        return roleMapper.selectOne(
                new LambdaQueryWrapper<Role>()
                        .eq(Role::getName, roleName)
        );
    }

    /**
     * 检查是否是最后一个管理员
     */
    private boolean isLastAdmin(Long userIdToRemove) {
        // 查询该用户是否为管理员
        TeamMember memberToRemove = teamMemberMapper.selectById(userIdToRemove);
        if (memberToRemove == null) {
            return false;
        }

        Role adminRole = getRoleByRoleName("admin");
        if (adminRole == null || !adminRole.getId().equals(memberToRemove.getRoleId())) {
            return false;
        }

        // 查询管理员数量
        List<TeamMember> adminMembers = teamMemberMapper.selectList(
                new LambdaQueryWrapper<TeamMember>()
                        .eq(TeamMember::getRoleId, adminRole.getId())
                        .eq(TeamMember::getTeamId, 1L) // 默认团队ID
        );

        // 如果只有一个管理员，且是要移除的用户，则返回true
        return adminMembers.size() == 1 &&
                adminMembers.get(0).getUserId().equals(userIdToRemove);
    }

    /**
     * 角色更新请求类
     */
    static class RoleUpdateRequest {
        private String role;

        public String getRole() {
            return role;
        }

        public void setRole(String role) {
            this.role = role;
        }
    }

    /**
     * 方向更新请求类
     */
    static class DirectionUpdateRequest {
        private String direction;

        public String getDirection() {
            return direction;
        }

        public void setDirection(String direction) {
            this.direction = direction;
        }
    }
}